package other.xsy.paas;

import com.rkhd.platform.sdk.data.model.Opportunity;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.xsy.paas.utils.HCXObjectService;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：描述describe__c发生变更时更新descriptionModificationDate__c为当前日期
 * 注意：仅修改该字段更新日期，创建时不更新日期
 *
 * @author whz
 * @ClassName: OpportunityTrigger
 * @Description:
 * @date 2024年03月30日
 */
public class OpportunityTrigger implements Trigger {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static Logger logger = LoggerFactory.getLogger();

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Opportunity> opportunityList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Opportunity opportunity = (Opportunity) xObject;
            opportunityList.add(opportunity);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        handler(opportunityList.get(0));
        return new TriggerResponse(true, "", dataResultList);
    }

    private void handler(Opportunity opportunity) {
        try {
            String opportunityName = opportunity.getOpportunityName();
            String describe = opportunity.getDescribe__c();
            logger.info("机会名称：" + opportunityName);
            Opportunity opportunityOld = new Opportunity();
            opportunityOld.setId(opportunity.getId());
            opportunityOld = hcxObjectService.get(opportunityOld);
            String describeOle = opportunityOld.getDescribe__c();
            logger.info("新；" + describe + "  旧：" + describeOle);
            if (StringUtils.isBlank(describe) && StringUtils.isBlank(describeOle)) {
                return;
            }
            describeOle = describeOle == null ? "" : describeOle;
            if (describeOle.equals(describe)) {
                return;
            }
            opportunity.setDescriptionModificationDate__c(System.currentTimeMillis());
        }catch (Exception e) {
            logger.error("系统异常：" + e.getMessage());
        }
    }
}
